<?php

namespace Modules\Api\Service;

use HiCommon\Repository\StoreCarRepository;
use HiCommon\Repository\GoodsProductRepository;

class StoreCarService
{
    /**
     * 数据验证
     * @param array $arrInput
     * @return array
     */
    public function check_data(array $arrInput)
    {
        if (empty($arrInput['type'])) {
            return ['state' => 1, 'msg' => '商品类型不能为空'];
        }
        if (empty($arrInput['shop_id'])) {
            return ['state' => 1, 'msg' => '门店id不能为空'];
        }
        if ($arrInput['type'] == 2 && empty($arrInput['activity_id'])) {
            return ['state' => 1, 'msg' => '活动id不能为空'];
        }
        if (empty($arrInput['goods_id'])) {
            return ['state' => 1, 'msg' => '商品id不能为空'];
        }
        if (empty($arrInput['goods_product_id'])) {
            return ['state' => 1, 'msg' => '产品id不能为空'];
        }
        if (empty($arrInput['goods_num'])) {
            return ['state' => 1, 'msg' => '商品数量不能为空'];
        }

        return $arrInput;
    }

    /**
     * 添加商品到购物车
     * @param array $arr_input
     * @return array
     */
    public function add_one(array $arr_input)
    {
        try {
            $temp = self::check_data((array)$arr_input);
            if ($temp['state'] == 1) {
                return $temp;
            }

            //检查该商品的该规格是否存在，如果存在就修改数量
            $map = ['user_id' => $arr_input['user_id'], 'goods_product_id' => $arr_input['goods_product_id'], 'type' => $arr_input['type']];
            $is_have = StoreCarRepository::get_one_by_where($map);
            $product = GoodsProductRepository::base_find_one((int)$arr_input['goods_product_id'], ['field' => 'stock']);
            if ($is_have->first()) {
                $num = $is_have->goods_num + $arr_input['goods_num'];
                if ($num > $product->stock) {
                    return hello_error('库存不足');
                }
                $result = StoreCarRepository::increase_num($is_have->id, 'goods_num', $arr_input['goods_num']);
            } else {
                if ((int)$arr_input['goods_num'] > $product->stock) {
                    return hello_error('库存不足');
                }
                $result = StoreCarRepository::add_one($arr_input)->toarray();
            }

            if (empty($result)) {
                return hello_error('添加失败');
            } else {
                return hello_success('添加成功', []);
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     * 获取购物车商品列表
     * @param array $data
     * @return array
     */
    public function get_list(array $data)
    {
        try {
            if (empty($data['type'])) {
                return hello_error('购物车类型不能为空');
            }
            $arr_option['where'] = ['type' => (int)$data['type'], 'user_id' => $data['user_id']];
            $arr_option['field'] = ['id', 'type', 'shop_id', 'user_id', 'activity_id', 'goods_id', 'goods_product_id', 'goods_num'];
            $arr_option['with'] = ['get_shop', 'get_product', 'get_activity', 'get_goods' => function ($query) use ($data) {
                if ($data['type'] == 1) {
                    $query->where('type', 1);
                } else {
                    $query->where('type', 3);
                }
            }];

            $arr_list = StoreCarRepository::get_all_by_where($arr_option)->toArray();

            $this_time = time();
            foreach ($arr_list as $key => $value) {
                if (!empty($value['get_goods'])) {
                    $activity_state = 0;
                    if ($data['type'] == 2 && !empty($value['get_activity'])) {
                        $over_time = $value['get_activity']['over_time'];
                        if ($over_time < $this_time) {
                            $activity_state = 1;//活动已过期
                        }
                    }
                    $list[$value['shop_id']]['shop'] = [
                        'shop_id' => $value['shop_id'],
                        'shop_name' => $value['get_shop']['name'],
                    ];
                    $list[$value['shop_id']]['goods'][] = [
                        'car_id' => $value['id'],
                        'goods_product_id' => $value['goods_product_id'],
                        'goods_id' => $value['goods_id'],
                        'goods_name' => $value['get_goods']['name'],
                        'goods_status' => $value['get_goods']['status'],
                        'goods_price' => $value['get_product']['price'],
                        'goods_num' => $value['goods_num'],
                        'goods_specs_name' => $value['get_product']['specs']['name'],
                        'goods_specs_pic' => $value['get_product']['pic']['full_src'],
                        'product_stock' => $value['get_product']['stock'],
                        'activity_id' => $value['activity_id'],
                        'activity_state' => $activity_state
                    ];
                }
            }

            if (empty($list)) {
                return hello_success('暂无数据');
            }

            return hello_success('查询成功', array_values($list));
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 加减购物车中商品数量
     * @param array $arr_input
     * @return array
     */
    public function change_num(array $arr_input)
    {
        try {
            if (empty($arr_input['car_id'])) {
                return hello_error('数据id不能为空');
            }
            if (empty($arr_input['type'])) {
                return hello_error('操作类型错误');
            }
            if ($arr_input['type'] == 1) {
                $arr_option['field'] = ['goods_product_id', 'goods_num'];
                $arr_option['with'] = ['get_product'];
                $product = StoreCarRepository::base_find_one((int)$arr_input['car_id'], $arr_option);
                if ($product->first()) {
                    $data = $product->toArray();
                    if ($data['goods_num'] >= $data['get_product']['stock']) {
                        return hello_error('库存不足！');
                    }
                } else {
                    return hello_error('参数错误');
                }

                $res = StoreCarRepository::increase_num($arr_input['car_id']);//递增1
            } else {
                $res = StoreCarRepository::decrease_num($arr_input['car_id']);//递减1
            }

            if ($res === false) {
                return hello_error('失败');
            }

            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改购物车中商品规格
     * @param array $arr_input
     * @return array
     */
    public function change_product(array $arr_input)
    {
        try {
            $car_id = (int)$arr_input['car_id'];
            if (empty($arr_input['car_id'])) {
                return hello_error('购物车id不能为空');
            }
            if (empty($arr_input['product_id'])) {
                return hello_error('规格id不能为空');
            }
            $product = GoodsProductRepository::base_find_one((int)$arr_input['product_id'], ['field' => 'stock']);
            if($product->first() && $product->stock == 0){
                return hello_error('库存不足！');
            }

            $up_data['goods_product_id'] = $arr_input['product_id'];
            $res = StoreCarRepository::edit_one(['id' => $car_id], $up_data);

            $arr_where = ['user_id' => $arr_input['user_id'], 'goods_product_id' => $arr_input['product_id']];
            $result = StoreCarRepository::get_by_where($arr_where, $car_id);
            if ($result) {
                StoreCarRepository::delete_one($result->id);
            }

            if ($res === false) {
                return hello_error('失败');
            }

            return hello_success('修改成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除一条数据
     * @param array $arr_input
     * @return array
     */
    public function delete(array $arr_input)
    {
        try {
            if (!empty($arr_input['empty_cart']) && $arr_input['empty_cart'] == 1) {//清空购物车
                if (empty($arr_input['type'])) {
                    return hello_error('清除的购物车类型不能为空');
                }
                $map = ['user_id' => $arr_input['user_id'], 'type' => (int)$arr_input['type']];

                $res = StoreCarRepository::delete_by_where($map);

            } else {

                $ids = hi_array_del_null($arr_input['car_id']);
                if (empty($ids)) {
                    return hello_error('数据id不能为空');
                }
                $res = StoreCarRepository::delete_by_where_in($ids);
            }

            if ($res === false) {
                return hello_error('删除失败');
            }

            return hello_success('删除成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取购物车中商品数量
     * @return mixed
     */
    public function get_car_goods_total()
    {
        $where['user_id'] = api_user_id();
        return StoreCarRepository::get_count_by_where($where);
    }
}